import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:tracker/common/constants/app_constants.dart';
import 'package:tracker/common/pay/model/order_info_resp.dart';
import 'package:wechat_kit/wechat_kit.dart';
import 'package:tracker/api/index.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/pay/model/wxpay_order_info_resp.dart';
import 'package:tracker/startup/env/env.dart';
import 'package:tracker/utils/toast_utils.dart';

import '../model/base_resp.dart';

const String kWechatAppID = 'wx50732cb2bfc2bcee';

// const String kWechatUniversalLink = 'applinks:www.ljwl.tech'; // iOS universalLink 通用链接设置
const String kWechatUniversalLink = 'https://www.ljwl.tech/'; // iOS universalLink 通用链接设置

class WxpayUtils {
  //声明回调参数
  late final StreamSubscription<WechatResp> _wechatRespSubs;
  WechatAuthResp? _wechatAuthResp; //保存授权的resp码，用于获取后续获取用户信息

  static Future<void> register() async {
    XLogger.info("registerApp");
    await WechatKitPlatform.instance.registerApp(
      appId: kWechatAppID,
      //不了解需要的话可以搜索ios universalLink 通用链接设置，能够直接通过链接唤起app
      universalLink: kWechatUniversalLink,
    );
  }

  static Future<void> handleInitialWXReq() {
    throw UnimplementedError();
  }
  //注册微信支付、分享、授权等回调
  void registerWechatResp(void Function(WechatResp resp) callback) {
    XLogger.info("registerWechatResp");
    _wechatRespSubs = WechatKitPlatform.instance.respStream().listen(callback);

  }

  void dispose() {
    try {
      _wechatRespSubs.cancel();
    } catch (e) {}
  }

  //监听回调，集多个回调与一身
  void listenWechatResp(WechatResp resp) {
    final String content = '基础: ${resp.errorCode} ${resp.errorMsg}';
    print("微信==== $content");
    if (resp is WechatAuthResp) {
      //可以保存下来授权的状态(没必要这个），用来获取用户信息
      _wechatAuthResp = resp;
      final String content = '登录: ${resp.errorCode} ${resp.errorMsg}';
      print(content);
    } else if (resp is WechatShareMsgResp) {
      final String content = '分享: ${resp.errorCode} ${resp.errorMsg}';
      print(content);
    } else if (resp is WechatPayResp) {
      final String content = '支付: ${resp.errorCode} ${resp.errorMsg}';
      print(content);
    } else if (resp is WechatLaunchMiniProgramResp) {
      //这里就不加入案例了
      final String content = '拉起小程序: ${resp.errorCode} ${resp.errorMsg}';
      XLogger.info(content);
    }
  }

  void launch91wl(String ticket) {
    XLogger.info('拉起HHMM小程序, ticket: $ticket');
    WechatKitPlatform.instance
        .launchMiniProgram(
      userName: Env.envConfig.wechatGhId,
      path: '${Env.envConfig.wechatMiniPath}?ticket=$ticket',
      type: Env.envConfig.wechatMiniProgramType,
    )
        .catchError((e) {
      XLogger.error('拉起微信小程序失败: $e');
    });
  }

  /// 拉起第三方的小程序
  void launchMiniApp(MiniAppInfo miniAppInfo,
      {String orderNo = '', String iccid = '', String imei = '', double goodsTotalPrice = 0}) {
    var path = miniAppInfo.jumpPath!;
    // 拼接参数
    // 单位分转为元，并且保留两位小数
    // goodsTotalPrice = (goodsTotalPrice * 100);
    var queryParams = <String, dynamic>{
      'orderNo': orderNo,
      'iccid': iccid,
      'imei': imei,
      'goodsTotalPrice': goodsTotalPrice.toStringAsFixed(2),
    };
    var queryString = queryParams.entries.map((entry) => '${entry.key}=${Uri.encodeComponent(entry.value)}').join('&');
    path = '$path?$queryString';
    XLogger.info('拉起小程序, userName: ${miniAppInfo.originalId}, path: $path');
    WechatKitPlatform.instance
        .launchMiniProgram(
      userName: miniAppInfo.originalId!,
      path: path,
      type: Env.envConfig.wechatMiniProgramType,
    )
        .catchError((e) {
      XLogger.error('拉起微信小程序失败: $e');
    });
  }

  void createOrder(String imei, int pacakgeId) async{
    // 判断是否安装微信
    final bool isInstalled = await WechatKitPlatform.instance.isInstalled();
    XLogger.info(WechatKitPlatform.instance.isInstalled());
    if (!isInstalled) {
      ToastUtils.showToast('请先安装微信');
      return;
    }
    ToastUtils.showLoading();
    final res = await get<WxpayOrderInfoResp, WxpayOrderInfoResp>('$newBaseULr/weixin/appPay?imei=$imei&packageId=$pacakgeId',decodeType: WxpayOrderInfoResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        WechatKitPlatform.instance.pay(appId: resp.data?.appid ?? "", partnerId: resp.data?.partnerId ?? "", prepayId: resp.data?.prepayId ?? "", package: resp.data?.packageValue ?? "", nonceStr: resp.data?.noncestr ?? "", timeStamp: resp.data?.timestamp ?? "", sign: resp.data?.sign ?? "");

      } else {
        ToastUtils.showToast(resp.msg ?? '创建支付失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('发送指令失败: msg: $msg, code: $code');
      ToastUtils.showToast('发送指令失败: msg: $msg, code: $code');
    });
  }
// 调用微信支付
  void handleWechatPay() async {

  }

  /// 微信sdk支付，创建订单
  // void createOrder(OrderInfoReq orderInfoReq) async {
  //   // 判断是否安装微信
  //   final bool isInstalled = await WechatKitPlatform.instance.isInstalled();
  //   XLogger.info(WechatKitPlatform.instance.isInstalled());
  //   if (!isInstalled) {
  //     ToastUtils.showToast('请先安装微信');
  //     return;
  //   }
  //   ToastUtils.showLoading();
  //   final res = await post<WxpayOrderInfoResp, WxpayOrderInfoResp>('',
  //       data: orderInfoReq.toJson(), decodeType: WxpayOrderInfoResp());
  //   res.when(success: (resp) {
  //     ToastUtils.dismissLoading();
  //     if (resp.code == 200) {
  //       // 创建订单成功
  //       if (Platform.isAndroid) {
  //         // 拉起微信支付
  //         var data = resp.data!;
  //         WechatKitPlatform.instance.pay(
  //             appId: data.appid!,
  //             partnerId: data.partnerId!,
  //             prepayId: data.prepayId!,
  //             package: data.packageValue!,
  //             nonceStr: data.noncestr!,
  //             timeStamp: data.timestamp!,
  //             sign: data.sign!);
  //       }
  //     } else {
  //       ToastUtils.showToast(resp.msg ?? '创建订单失败');
  //     }
  //   }, failure: (String msg, int code) {
  //     ToastUtils.showToast('创建订单失败');
  //   });
  // }

  /// 创建小程序预生成订单（第三方自己开发的）
  void createMiniAppOrder(OrderInfoReq orderInfoReq) async {
    // 判断是否安装微信
    final bool isInstalled = await WechatKitPlatform.instance.isInstalled();
    if (!isInstalled) {
      ToastUtils.showToast('请先安装微信');
      return;
    }
    var orderInfo = await PayApi.createExternalPreOrder(orderInfoReq);
    if (orderInfo == null) {
      return;
    }
    if (orderInfo.miniAppInfo == null) {
      ToastUtils.showToast('未配置小程序');
      return;
    }
    launchMiniApp(orderInfo.miniAppInfo!,
        imei: orderInfo.imei!, iccid: '', orderNo: orderInfo.orderNo!, goodsTotalPrice: orderInfo.goodsTotalPrice!);
  }

  void createVip(int? packageId, String imei, double? price) async {
    // 判断是否安装微信
    final bool isInstalled = await WechatKitPlatform.instance.isInstalled();
    if (!isInstalled) {
      ToastUtils.showToast('请先安装微信');
      return;
    }
    XLogger.info('点击微信了');

    ToastUtils.showLoading();
    final res = await get<WxpayOrderInfoResp, WxpayOrderInfoResp>(
        '$newBaseULr/weixin/appPay?imei=$imei&packageId=$packageId',
        decodeType: WxpayOrderInfoResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        WechatKitPlatform.instance.pay(appId: resp.data?.appid ?? "",
            partnerId: resp.data?.partnerId ?? "",
            prepayId: resp.data?.prepayId ?? "",
            package: resp.data?.packageValue ?? "",
            nonceStr: resp.data?.noncestr ?? "",
            timeStamp: resp.data?.timestamp ?? "",
            sign: resp.data?.sign ?? "");
      } else {
        ToastUtils.showToast(resp.msg ?? '创建支付失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('发送指令失败: msg: $msg, code: $code');
      ToastUtils.showToast('发送指令失败: msg: $msg, code: $code');
    });
  }


    void createChargeSIMCard(int? packageId, String iccid) async {
      // 判断是否安装微信
      final bool isInstalled = await WechatKitPlatform.instance.isInstalled();
      if (!isInstalled) {
        ToastUtils.showToast('请先安装微信');
        return;
      }
      XLogger.info('点击微信了');

      ToastUtils.showLoading();
      final res = await get<WxpayOrderInfoResp, WxpayOrderInfoResp>(
          '$newBaseULr/sim/weixin/appPay?iccid=$iccid&packageId=$packageId',
          decodeType: WxpayOrderInfoResp());
      res.when(success: (resp) {
        ToastUtils.dismissLoading();
        if (resp.code == 200) {
          WechatKitPlatform.instance.pay(appId: resp.data?.appid ?? "",
              partnerId: resp.data?.partnerId ?? "",
              prepayId: resp.data?.prepayId ?? "",
              package: resp.data?.packageValue ?? "",
              nonceStr: resp.data?.noncestr ?? "",
              timeStamp: resp.data?.timestamp ?? "",
              sign: resp.data?.sign ?? "");
        } else {
          ToastUtils.showToast(resp.msg ?? '创建支付失败');
        }
      }, failure: (String msg, int code) {
        XLogger.error('发送指令失败: msg: $msg, code: $code');
        ToastUtils.showToast('发送指令失败: msg: $msg, code: $code');
      });
    }

    // WechatKitPlatform.instance
    //     .launchMiniProgram(
    //   userName: "gh_7578ee9778d0",
    //   type: 0,//Env.envConfig.wechatMiniProgramType,// 小程序环境
    //   path: "/pages/index/index?imei=$imei&packageId=$packageId&money=$price",
    // ).then((success) {
    //   XLogger.info('拉起微信小程序成功');
    // })
    //     .catchError((e) {
    //   XLogger.error('拉起微信小程序失败: $e');
    // });


}
